package com.st.event.demo.source;

import org.springframework.core.MethodClassKey;
import org.springframework.lang.Nullable;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractEventAttributeSource implements EventAttributeSource {

    private final Map<Object, EventAttribute> attributeCache = new ConcurrentHashMap<>(16);

    @Override
    public EventAttribute getPayAttribute(Method method, Class<?> targetClass) {
        System.out.println("执行15-----------");
        if (method.getDeclaringClass() == Object.class) {
            return null;
        }

        Object cacheKey = getCacheKey(method, targetClass);
        EventAttribute eventAttribute = this.attributeCache.get(cacheKey);
        if (eventAttribute != null) {
            return eventAttribute;
        }

        EventAttribute attr = computeEventAttribute(method);
        if (attr != null) {
            this.attributeCache.put(cacheKey, attr);
        }

        return attr;
    }

    protected EventAttribute computeEventAttribute(Method method) {
        EventAttribute attr = findEventAttribute(method);
        if (attr != null) {
            return attr;
        }
        return null;
    }

    protected abstract EventAttribute findEventAttribute(Method method);

    protected Object getCacheKey(Method method, @Nullable Class<?> targetClass) {
        return new MethodClassKey(method, targetClass);
    }
}
